<template>
  <div
    class="drag-box"
    @dragstart.stop="onDragstart"
    @dragend.stop="onDragend"
    :style="pos"
    draggable="true"
  >
    <slot />
  </div>
</template>
<style scoped>
.drag-box {
  opacity: 0.3;
}
.drag-box:hover {
  opacity: 1;
}
</style>
<script>
/**
 * 可任意拖动的组件
 *
 * todo 遗留拖动过程中的鼠标样式问题
 */
export default {
  name: 'DragBox',
  props: {
    init: Object,
  },
  data() {
    const point = { x: 0, y: 0 };
    if (this.init.x) {
      point.x = this.init.x;
    }

    if (this.init.y) {
      point.y = this.init.y;
    }

    return {
      point: point,
      sub: point,
      pos: { top: point.y + 'px', left: point.x + 'px' },
    };
  },
  created() {},
  methods: {
    onDragstart(e) {
      this.point = {
        x: e.screenX,
        y: e.screenY,
      };
    },
    onDragend(e) {
      this.setPos({
        x: (this.sub.x += e.screenX - this.point.x),
        y: (this.sub.y += e.screenY - this.point.y),
      });
    },
    setPos(point) {
      this.sub = point;
      this.pos = { top: point.y + 'px', left: point.x + 'px' };
    },
  },
};
</script>

<style scoped>
.drag-box {
  position: fixed;
  z-index: 99999;
  background-color: #00000077;
  min-width: 24px;
  min-height: 24px;
  cursor: pointer;
}
</style>
